import runtime, {
  async
} from '../../lib/runtime/runtime'
import request from '../../request/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    pagenum: 1, //请求第几页
    total: 1, //总数
    pagesize: 5, //一页请求多少条
    goodList: [],
    navData: [{
        name: '综合',
        id: 1,
        active: true
      },
      {
        name: '销量',
        id: 2,
        active: false
      },

      {
        name: '价格',
        id: 3,
        active: false
      },
    ]
  },

  //获取数据
  async getGoodList(cid, pagenum, pagesize) {
    wx.showLoading({
      title: '加载中...',
    })
    let
      res = await request('/goods/search', {
        params: {
          cid: cid,
          pagenum: pagenum,
          pagesize: pagesize
        }
      })
    let {
      total
    } = res
    this.setData({
      goodList: [...this.data.goodList, ...res.goods],
      total: total
    })
    console.log(this.data.goodList);
  },

  myChangeIndex(data) {
    let newNavData = this.data.navData.map((item, index) => {
      if (index == data.detail.index) {
        item.active = true
        return item
      } else {
        item.active = false
        return item
      }
    })
    this.setData({
      navData: newNavData
    })
  },

  //页面跳转
  GoToDetail(e) {
    let {
      gid
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/goods_detail/index?gid=' + gid,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {
      cid
    } = options
    this.setData({
      id: cid
    })
    this.getGoodList(cid, this.data.pagenum, this.data.pagesize)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function (options) {
    this.setData({
      goodList: [],
      pagenum: 1
    })
    wx.stopPullDownRefresh({
      success: (res) => {
        this.getGoodList(this.data.id, this.data.pagenum, this.data.pagesize)
      },
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.goodList.length >= this.data.total) {
      wx.showToast({
        title: '没有更多数据了',
      })
    } else {
      this.setData({
        pagenum: this.data.pagenum + 1
      })
      this.getGoodList(this.data.id, this.data.pagenum, this.data.pagesize)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})